package edu.java.texbooks.scjp.threads.test04.mailbox.extra;

public class Mailbox {

	// --- Instance Variables -----------------------------------------
	private String message = null;
	private boolean request = false;

	// --- Constructors -----------------------------------------------
	public Mailbox() {

	}

	public Mailbox(String message, boolean request) {
		this.message = message;
		this.request = request;
	}

	// --- Methods ----------------------------------------------------
	public synchronized void storeMessage(String message) {
		while (request == true) {
			try {
				wait();
			} catch (InterruptedException ie) {
				System.out
						.println("Thread interrupted in storeMessage() method");
			}
		}

		// request here is false
		this.message = message;
		request = true;
		notifyAll();
	}

	public synchronized String retrieveMessage() {
		while (request == false) {
			try {
				wait();
			} catch (InterruptedException ie) {
				System.out
						.println("Thread interrupted in retrieveMessage() method");
			}
		}

		// here request is true
		request = false;
		notifyAll();
		return message;
	}
}
